#!/bin/bash

# set -ex

COIN_REPO=`pwd`

pull_pi_repo_impl()
{
  if [ -d "$1" ]; then
    cd "$1" && git checkout . && git pull
  fi
  cd $COIN_REPO
}

pull_pi_repo()
{
  # if mea is specified, do not pull the coin_product_info repo to avoid
  # PI is override when there are multiple strategies are running on same instance
  if [ $# -eq 0 ]; then
    pull_pi_repo_impl "../coin_product_info/data"
    pull_pi_repo_impl "../../coin_product_info/data"
    pull_pi_repo_impl "~/workspace/coin_product_info/data"
  fi
}

sync_pi_repo_impl()
{
  if [ -d "$2" ]; then
    trading_date=`date +'%Y%m%d'`
    src=$1
    dst="${2}${trading_date}/"
    if [ $# -eq 3 ]; then
      mea=$3
      src="${src}${mea}.json"
      dst="${dst}${mea}.json"
    fi
    rsync -avz "$src" "$dst"
  fi
  cd $COIN_REPO
}

sync_pi_repo()
{
  if [ $# -eq 0 ]; then
    sync_pi_repo_impl "data/coin2/product_info/" "../coin_product_info/data/"
    sync_pi_repo_impl "data/coin2/product_info/" "../../coin_product_info/data/"
    sync_pi_repo_impl "data/coin2/product_info/" "~/workspace/coin_product_info/data/"
  else
    sync_pi_repo_impl "data/coin2/product_info/" "../coin_product_info/data/" "$1"
    sync_pi_repo_impl "data/coin2/product_info/" "../../coin_product_info/data/" "$1"
    sync_pi_repo_impl "data/coin2/product_info/" "~/workspace/coin_product_info/data/" "$1"
  fi
}

update_pi_local()
{
  if [ $# -eq 0 ]; then
    # update all MEAs
    pull_pi_repo
    ./pyrunner python/coin2/support/product_info/run.py
    sync_pi_repo
  else
    # update specify MEA
    pull_pi_repo "$1"
    ./pyrunner python/coin2/support/product_info/run.py --mea="$1"
    sync_pi_repo "$1"
  fi
}

wait_until_pi_is_ready()
{
  driver=$1
  mea=""
  if [ $# -eq 2 ]; then
    mea=$2
  fi

  # loop until pi is ready
  while :
  do
    update_pi_local $mea

    cmd="./pyrunner cc/experimental/wliang/utils/check_pi_is_ready.py --driver=$driver"
    ret=`$cmd`
    if [ "$ret" == "SUCCESS" ]; then
      break;
    fi

    echo "pi is not ready. retry after 5s"
    sleep 5
  done
}
